package com.forum.Service.Impl;

import com.common.Utils.JwtUtil;
import com.forum.Entity.Topic;
import com.forum.Mapper.TopicMapper;
import com.forum.Service.TopicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    private TopicMapper topicMapper;


    @Override
    public PageInfo<Topic> getTopicList(Integer pageNum, Integer pageSize, String topicName) {
        PageHelper.startPage(pageNum,pageSize);
        List<Topic> topicList = topicMapper.getTopicList(topicName);
        return new PageInfo<>(topicList);
    }

    @Override
    public List<Topic> getTopicLists() {
        return  topicMapper.getTopicLists();
    }

    @Override
    public PageInfo<Topic> getTopicListByThree(Integer pageNum, Integer pageSize, String topicName, String username) {
        PageHelper.startPage(pageNum,pageSize);
        List<Topic> topicList = topicMapper.getTopicListByThree(topicName,username);
        return new PageInfo<>(topicList);
    }

    @Override
    public void addTopic(Topic topic) {
        String token = topic.getToken();
        String Username = JwtUtil.extractUsername(token);
        topic.setCreateUser(Username);
        topic.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        topic.setTopicId(makeId());
        topicMapper.addTopic(topic);

    }

    private String makeId() {
        return "T" + System.currentTimeMillis();
    }

    @Override
    public void updateTopic(Topic topic) {
        String token = topic.getToken();
        String Username = JwtUtil.extractUsername(token);
        topic.setUpdateUser(Username);
        topic.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        topicMapper.updateTopic(topic);

    }

    @Override
    public void deleteTopic(String topicId) {
        topicMapper.deleteTopic(topicId);

    }


}
